<?php

//定时任务相关控制器

namespace hotel\modules\api\controllers;

use hotel\common\models\Activity;
use hotel\common\models\ActivityLog;
use hotel\common\models\ActivityDate;
use hotel\common\models\App;
use hotel\common\models\OrdersModel;
use hotel\common\utils\CommonFun;
use hotel\common\utils\HotelServices;
use hotel\common\utils\PayServices;
use hotel\common\utils\Tool;
use Yii;
use yii\log\FileTarget;


class ActivityController extends CoreController
{
    //获取活动列表
    public function actionGetActivity()
    {
        $data = Activity::find()->asArray()->all();
        $now_time = date('Y-m-d H:i:s');
        foreach ($data as $k => $v) {
            $end_time = $v['end_time'];
            if ($end_time < $now_time) {
                $data[$k]['is_end'] = 1;
            } else {
                $data[$k]['is_end'] = 2;
            }
            $activity_id = $v['id'];
            $res = ActivityLog::find()->where("activity_id = $activity_id and member_id = $this->member_id and order_state = 2")->asArray()->one();
            if ($res) {
                $data[$k]['is_sign'] = 1;
            } else {
                $data[$k]['is_sign'] = 2;
            }
        }
        return Tool::showRes([0, '获取活动列表成功'], $data);
    }

    //获取活动详情
    public function actionGetActivityDetail()
    {
        $request = \Yii::$app->request;
        $post_data = $request->post();
        $activity_id = $post_data['activity_id'];
        $data = Activity::find()->where("id = $activity_id")->asArray()->one();
        if(empty($data)){
            return Tool::showRes([400, '活动参数有误']);
        }
        $now_time = date('Y-m-d H:i:s');
        $end_time = $data['end_time'];
        if ($end_time < $now_time) {
            $data['is_end'] = 1;
        } else {
            $data['is_end'] = 2;
        }
        $res = ActivityLog::find()->where("activity_id = $activity_id and member_id = $this->member_id and order_state = 2")->asArray()->one();
        if ($res) {
            $data['is_sign'] = 1;
        } else {
            $data['is_sign'] = 2;
        }
        $date_arr = ActivityDate::find()->where("activity_id = $activity_id")->asArray()->all();
        $data['date_arr'] = $date_arr;
        return Tool::showRes([0, '获取活动详情成功'], $data);
    }

    public function actionPlaceOrder(){
        $request = \Yii::$app->request;
        $post_data = $request->post();
        $activity_id = $post_data['activity_id'];
        $date = $post_data['date'];
        $activity_data = Activity::find()->where("id = $activity_id")->asArray()->one();
        if(empty($activity_data)){
            return Tool::showRes([400, '活动参数有误']);
        }
        $num = ActivityLog::find()->where("order_state = 2 and date='$date'")->count();
        $number_of_people = $activity_data['number_of_people'];
        if($num >= $number_of_people){
            return Tool::showRes([400, '超出报名人数']);
        }
        $price = $activity_data['price'];
        if($price == 0){
            $order_state = 2;
        }else{
            $order_state = 1;
        }
        //保存订单到数据库
        $order_sn = CommonFun::makeRandSn($this->member_id);
        $model = New ActivityLog();
        $model->member_id = $this->member_id;
        $model->order_sn = $order_sn;
        $model->activity_id = $activity_id;
        $model->pay_price = $price;
        $model->date = $date;
        $model->name = $post_data['name'];
        $model->phone = $post_data['phone'];
        $model->order_state = $order_state;
        $model->create_time = date('Y-m-d H:i:s');
        if ($model->save()) {
            if($price == 0){
                return Tool::showRes([0, '下单成功']);
            }else{
                $res = PayServices::activityPay($this->openid, $price * 100, $order_sn, '活动', '活动');
                if ($res) {
                    return Tool::showRes([0, '拉起支付成功'], $res);
                } else {
                    return Tool::showRes([400, '拉起支付失败']);
                }
            }
        }else {
            return Tool::showRes([400, '下单失败']);
        }
    }





    /*
    * 支付成功回调
    */
    public function actionActivityCallBack()
    {
        $request = \Yii::$app->request;
        $post_data = $request->post();
        $this->recordPay($post_data);
        $payNo = $post_data['payNo'];
        $order = OrdersModel::find()->where("order_sn = '$payNo'")->asArray()->one();
        $appid = $order['appid'];
        $app_data = App::find()->where("appid = '$appid'")->asArray()->one();
        $data['appId'] = $post_data['appId'];
        $data['payStatus'] = $post_data['payStatus'];
        $data['payNo'] = $post_data['payNo'];
        $data['payTime'] = $post_data['payTime'];
        $data['orderSn'] = $post_data['orderSn'];
        $data['nonceStr'] = $post_data['nonceStr'];
        $data['timeStamp'] = $post_data['timeStamp'];
        $c_sign = PayServices::computeSign($data, false, $app_data['pay_key']);
        $sign = $post_data['sign'];
        if ($sign != $c_sign) {
            $res = ['relCode' => 400, 'relMsg' => '签名错误'];
            return json_encode($res, JSON_UNESCAPED_UNICODE);
        }
        if ($data['payStatus'] != '00') {
            $res = ['relCode' => 400, 'relMsg' => '支付未成功'];
            return json_encode($res, JSON_UNESCAPED_UNICODE);
        }

        if ($order['order_state'] >= '2') {
            $res = ['relCode' => 400, 'relMsg' => '订单已经支付过了'];
            return json_encode($res, JSON_UNESCAPED_UNICODE);
        }

        try {
            //更新订单
            $data = array(
                'pay_time' => date("Y-m-d H:i:s"),
                'payment_code' => 'weixin',
                'order_state' => 2,
            );
            $flag = OrdersModel::updateAll($data, ['order_sn' => $order['order_sn']]);
            if ($flag) {
                $session = HotelServices::checkXopSession($appid);
                //西软订单下单
                $dailyrate = [];
                $order_detail = json_decode($order['order_ddetail'], true);
                $days = count($order_detail);
                $fenmu = $days * $order['rmnum'];
                foreach ($order_detail as $k => $v) {
                    $dailyrate[$k]['rate'] = $v['rate'];
                    $dailyrate[$k]['date'] = $v['date'];
                    $dailyrate[$k]['pkg'] = $order['pkg'];
                    $dailyrate[$k]['rmrate'] = $order['pau_price'] / $fenmu;
                    $dailyrate[$k]['rtreason'] = '099';
                    $dailyrate[$k]['ratecode'] = $order['ratecode'];
                }
                $res = HotelServices::xopsavereservation($session, $appid, $order, $dailyrate);
                if ($res['success'] == 1) {
                    //更新订单xop状态已下单
                    $data = array(
                        'rsvno' => $res['results'][0]['rsvno'],
                        'accnt' => $res['results'][0]['accnt'],
                        'opx_state' => 2,
                    );
                    OrdersModel::updateAll($data, ['order_sn' => $order['order_sn']]);
                    //请求西软修改订单状态
                    $order_data = OrdersModel::find()->where("order_sn = '$payNo'")->asArray()->one();
                    $res1 = HotelServices::xopdopaymentaccount($session, $appid, $order_data);
                    if ($res1['success'] == 1) {
                        //更新订单xop状态已入账
                        $data = array(
                            'opx_state' => 3,
                        );
                        OrdersModel::updateAll($data, ['order_sn' => $order['order_sn']]);
                        $res = ['relCode' => 0, 'relMsg' => '订单更新成功'];
                        return json_encode($res, JSON_UNESCAPED_UNICODE);
                    } else {
                        $res = ['relCode' => 400, 'relMsg' => 'xop订单入账失败'];
                        return json_encode($res, JSON_UNESCAPED_UNICODE);
                    }
                } else {
                    $res = ['relCode' => 400, 'relMsg' => 'xop保存订单失败'];
                    return json_encode($res, JSON_UNESCAPED_UNICODE);
                }

            }

        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }


    protected function recordPay($options)
    {
        $log = new FileTarget();
        $log->logFile = \Yii::$app->getRuntimePath() . '/logs/task' . date('Ymd') . '.log';
        $log->messages[] = [
            json_encode($options)
        ];
        $log->export();
    }


}
